<template>
  <div>

    <!--    搜索区-->
    <vxe-form
      ref="formRef"
      :data="formData"
      size="small"
      @submit="submitEvent"
      @reset="resetEvent">


      <vxe-form-item title="姓名" field="keyword" span="5" :item-render="{}">
        <template #default="params">
          <vxe-input v-model="formData.keyword" placeholder="请输入"></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="是否为后勤人员" field="izHouQin" span="5" :item-render="{}">
        <template #default="params">
          <vxe-select v-model="formData.izHouQin" placeholder="请选择" clearable>
            <vxe-option value="后勤人员" label="后勤人员"></vxe-option>
            <vxe-option value="车间人员" label="车间人员"></vxe-option>
          </vxe-select>
        </template>
      </vxe-form-item>
      <vxe-form-item title="日期" field="year" span="5" :item-render="{}">
        <template #default="params">
          <vxe-date-picker v-model="formData.year" type="year"></vxe-date-picker>
        </template>
      </vxe-form-item>
      <vxe-form-item title="所在群聊" field="openConversationId" span="5" :item-render="{}">
        <template #default="params">
          <ApiSelect
            v-model:value="formData.openConversationId"
            v-bind="selectOption"
            placeholder="请选择"
          ></ApiSelect>
        </template>
      </vxe-form-item>
      <vxe-form-item  span="4" :item-render="{}">
        <template #default>
          <vxe-button type="submit" status="primary" content="查询" :loading="loading"></vxe-button>
          <vxe-button type="reset" content="重置" :loading="loading"></vxe-button>
        </template>
      </vxe-form-item>
    </vxe-form>

    <BasicTable
      title="出勤率统计"
      :columns="columns"
      :dataSource="data"
      :bordered="border"
      :striped="striped"
      :canResize="canResize"
      :loading="loading"
      :pagination="pagination"
      @change="changeFn"
      @columns-change="handleColumnChange"
    >
      <template #toolbar>
<!--        <div class="Table_i">-->
<!--          <label style="width: 100px">姓名:</label>-->
<!--          <Input v-model:value="keyword" placeholder="请输入姓名"></Input>-->
<!--        </div>-->
<!--        <div class="Table_i">-->
<!--          <label style="width: 100px; padding-top: 10px">日期:</label-->
<!--          ><Calendar-->
<!--            format="YYYY-MM"-->
<!--            :fullscreen="false"-->
<!--            v-model:value="year"-->
<!--            mode="year"-->
<!--            @panelChange="onPanelChange"-->
<!--          ></Calendar>-->
<!--        </div>-->
<!--        <div class="Table_i" style="width: 300px">-->
<!--          <label style="width: 100px">所在群聊:</label>-->
<!--          <ApiSelect-->
<!--            v-model:value="openConversationId"-->
<!--            v-bind="selectOption"-->
<!--            placeholder="请选择"-->
<!--          ></ApiSelect>-->
<!--        </div>-->
        <Button @click="aoaToExcel"> 导出excel</Button>
<!--        <Button @click="reload">重置</Button>-->

<!--        <Button type="primary" @click="searchFn">查询</Button>-->

        <RedoOutlined @click="reload" />
      </template>
    </BasicTable>

<!--    <FormModal @register="register" @success="handleSuccess" />-->
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, ColumnChangeParam } from '@/components/Table';
  import { RedoOutlined } from '@ant-design/icons-vue';
  import { BasicForm, useForm, ApiSelect } from '@/components/Form';
  import { dutyTableListApi, allChatGroupListApi } from '@/api/sys/sysData';
  import { ref, onMounted, h } from 'vue';
  import { DatePicker, Calendar, Tag, Input, Button,Select } from 'ant-design-vue';

  import FormModal from './FormModal.vue';
  import util from '@/utils/util';
  import { searchFormSchema } from './role.data';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';
  import { aoaToSheetXlsx, jsonToSheetXlsx } from '@/components/Excel';
  import { style } from '@logicflow/extension/es/bpmn-elements/presets/icons';
  import { log } from 'vxe-table';

  defineOptions({ name: 'integralList' });
  const { createMessage } = useMessage();

  const selectOption = ref({
    api: allChatGroupListApi,
    // mode: 'multiple',
    resultField: 'data',
    labelField: 'name',
    valueField: 'openConversationId',
    style: { width: '100%' },
  });

  const data = ref([]);
  const canResize = ref(false);
  const loading = ref(false);
  const striped = ref(true);
  const border = ref(true);

  const page = ref(1);
  const pageSize = ref(50);
  const keyword = ref('');
  const pagination = ref<any>({
    pageSize: 50,
  });

  const selectValue=ref("");
  const options=ref([
    {label:"后勤人员",value:"后勤人员"},
    {label:"车间人员",value:"车间人员"}

  ])

  const formData=ref({
  });

  const year = ref('');
  const openConversationId = ref();
  const excel_header = ref({
    userName: '姓名',
  });
  const base_excel_header_arr = ['userName'];
  const excel_header_arr = ref([]);

  const base_columns = [
    {
      title: '月份',
      dataIndex: 'month',
      children: [
        {
          title: '姓名',
          dataIndex: 'userName',
          width: 80,
        },
        {
          title: '人员类型',
          dataIndex: 'izHouQin',
          // format: (value: number) => {
          //   let v="";
          //   console.log("---text:", value);
          //   switch (value) {
          //     case 1:
          //       v="后勤人员";
          //       break;
          //     case 2:
          //       v="车间人员";
          //       break;
          //   }
          //   return v;
          // },
          width: 80,
        },
      ],
    },
  ];
  const columns = ref([]);

  function handleColumnChange(data: ColumnChangeParam[]) {
    console.log('ColumnChanged', data);
  }

  function reload() {
    year.value = '';
    keyword.value = '';
    page.value = 1;
    pageSize.value = 50;
    searchFn();
  }

  function changeFn(res) {
    // console.log(res)
    page.value = res.current;
    pageSize.value = res.pageSize;
    searchFn();
  }

  function searchFn() {
    let json = {
 //     year: year.value,
      page: page.value,
      keyword: keyword.value,
      pageSize: pageSize.value,
   //   openConversationId: openConversationId.value,
    };

    for(let k  in formData.value){
      if(formData.value[k]){
        json[k]=formData.value[k];
      }
    }
    if(json.year){
      json.year=json.year.replace("-01-01", '');
    }
    loading.value = true;
    // pagination.value.pageSize= pageSize;
    let let_columns = util.copy(base_columns);
    dutyTableListApi(json).then((res) => {
      loading.value = false;

      if (res.code == 200) {
        let list = res.data.dataList.list;
        excel_header.value = { userName: '姓名' };
        list.forEach((r) => {
          for (let key in r) {
            if (r[key]) {
              if (key.indexOf('isAll') != -1) {
                let isAllValue = '';
                if (r[key] == 1) {
                  isAllValue = '全勤';
                }
                r[`${key}Value`] = isAllValue;
              }

              if (key.indexOf('isFull') != -1) {
                let isFullValue = '';
                if (r[key] == 1) {
                  isFullValue = '满勤';
                }
                r[`${key}Value`] = isFullValue;
              }
            }
          }
        });
        data.value = list;
        pagination.value.total = res.data.dataList.totalResult;
        let months = res.data.months;
        let excel_arr = util.copy(base_excel_header_arr);
        months.forEach((row) => {
          let index_tx = parseInt(row.monthNo);
          let item_json = {
            title: index_tx + '月份',
            children: [
              {
                title: '当月天数',
                dataIndex: 'days' + row.monthNo,
                width: 80,
              },
              {
                title: '应到',
                dataIndex: 'shouldNum' + row.monthNo,
                width: 80,
              },
              {
                title: '实到',
                dataIndex: 'realNum' + row.monthNo,
                width: 80,
              },
              {
                title: '月满勤',
                dataIndex: 'isFull' + row.monthNo + 'Value',
                width: 80,
                // customRender: ({ record }) => {
                //   const value = record[`isFull${row.monthNo}`];
                //   const enable = ~~value === 1;
                //   const color = enable ? 'green' : 'red';
                //   const text = enable ? '是' : '否';
                //   return h(Tag, { color: color }, () => text);
                // },
              },
              {
                title: '月全勤',
                dataIndex: 'isAll' + row.monthNo + 'Value',
                width: 80,
                // customRender: ({ record }) => {
                //   const value = record[`isAll${row.monthNo}`];
                //   const enable = ~~value === 1;
                //   const color = enable ? 'green' : 'red';
                //   const text = enable ? '是' : '否';
                //   return h(Tag, { color: color }, () => text);
                // },
              },
            ],
          };

          // let header=excel_header.value;
          excel_header.value[`days${row.monthNo}`] = index_tx + '月天数';
          excel_header.value[`shouldNum${row.monthNo}`] = index_tx + '月应到';
          excel_header.value[`realNum${row.monthNo}`] = index_tx + '月实到';
          excel_header.value[`isFull${row.monthNo}Value`] = index_tx + '月满勤';
          excel_header.value[`isAll${row.monthNo}Value`] = index_tx + '月全勤';

          excel_arr.push(`days${row.monthNo}`);
          excel_arr.push(`shouldNum${row.monthNo}`);
          excel_arr.push(`realNum${row.monthNo}`);
          excel_arr.push(`isFull${row.monthNo}Value`);
          excel_arr.push(`isAll${row.monthNo}Value`);

          let_columns.push(item_json);
        });
        let d1 = {
          title: '24天完成率(%)',
          dataIndex: 'shouldRate',
          width: 80,
        };
        let d2 = {
          title: '30天完成率(%)',
          dataIndex: 'allRate',
          width: 80,
        };
        let_columns.push(d1);
        let_columns.push(d2);
        excel_header.value[`shouldRate`] = '24天完成率(%)';
        excel_header.value[`allRate`] = '30天完成率(%)';

        excel_arr.push('shouldRate');
        excel_arr.push('allRate');

        columns.value = let_columns;
        excel_header_arr.value = excel_arr;
      } else {
        createMessage.error(res.message);
      }
    });
  }

  function onPanelChange(value, mode) {
    // let arr=value.$y;
    let text = value.$y + '';
    console.log(text);
    year.value = text;
    searchFn();
  }

  onMounted(() => {
    searchFn();
    // console.log(util.times("year"))
  });

  function aoaToExcel() {
    // 保证data顺序与header一致
    let y = ''; //util.times('year') + ''
    y = year.value.$y;
    // console.log('---年-', y);
    // return;
    // let arrHeader=[ "姓名","职级"];
    let arr = data.value;
    let new_arr = [];
    arr.forEach((r) => {
      let json = {};
      for (let key in excel_header.value) {
        json[key] = r[key];
      }
      new_arr.push(json);
    });
    // aoaToSheetXlsx({
    //   data: [arr],
    //   header: arrHeader,
    //   filename: y+'读书打卡统计.xlsx',
    // });
    // console.log("--excel_header_arr",excel_header_arr.value)
    // return;
    jsonToSheetXlsx({
      data: new_arr,
      header: excel_header.value,
      filename: y + '读书打卡统计.xlsx',
      json2sheetOpts: {
        // 指定顺序
        header: excel_header_arr.value,
      },
    });
  }

  /**
   * ------------
   */

  function handleSuccess() {}


  function submitEvent({data}) {
   // console.log("--submitEvent:",data);
    searchFn()
  }
  function resetEvent(e){
    searchFn()

  }


</script>
<style lang="less">
  //使日历面板不显示
  .vben-basic-table-header__toolbar {
    .ant-picker-panel {
      display: none;
    }
  }
  .group {
    display: flex;
    justify-items: center;
    background: white;
    width: 100%;
    margin: 20px 10px;
    padding: 15px 10px;
    .ant-picker-panel {
      display: none;
    }
    .group_i {
      display: flex;
      width: 100%;
      .group_i_r {
        display: flex;
      }
    }
  }
  .Table_i {
    display: flex;
    justify-items: center;
    text-align: center;
    margin-right: 20px;
  }
</style>
